package cn.melonlib.cores.aop.comp.inject;

import cn.hutool.core.bean.BeanUtil;
import cn.melonlib.cores.commons.comp.utils.AdvancedStringUtils;
import cn.melonlib.cores.identification.comp.messenger.IdentificationMessenger;
import cn.melonlib.cores.identification.model.entity.Identification;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;

@Component
public class FilterRecordInterceptor extends ApplicationObjectSupport implements MethodInterceptor {



    @Nullable
    @Override
    public Object invoke(@NotNull MethodInvocation methodInvocation) throws Throwable {
        IdentificationMessenger identificationMessenger=this.getApplicationContext().getBean(IdentificationMessenger.class);
        Arrays.stream(methodInvocation.getArguments()).forEach(arg->{
            Identification identification=identificationMessenger.getIdentification();
            String id= AdvancedStringUtils.defaultIfBlank(BeanUtil.getProperty(identification,"openid"),
                    ()->BeanUtil.getProperty(identification,"account"),
                    ()->BeanUtil.getProperty(identification,"id"),()->""
            );
            String code = AdvancedStringUtils.defaultIfBlank(
                    BeanUtil.getProperty(identification,"username"),
                    ()->BeanUtil.getProperty(identification,"loginName"),
                    ()->BeanUtil.getProperty(identification,"usercode"),
                    ()->BeanUtil.getProperty(identification,"userCode"),
                    ()->BeanUtil.getProperty(identification,"code"),
                    ()->BeanUtil.getProperty(identification,"account"),()->""
            );
            if(arg instanceof Map){
                ((Map<String, Object>) arg).put("creatorId", JsonMap.createMap().append("eq",id));
                ((Map<String, Object>) arg).put("creatorCode", JsonMap.createMap().append("eq",code));
            }
        });

        return methodInvocation.proceed();
    }
}
